package com.simple.shiro;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import com.simple.entity.CodeResult;
import com.simple.entity.StatusCode;

/**
 * 全局异常
 */
@RestControllerAdvice
public class GlobalException {
	
	private static final Logger logger = LoggerFactory.getLogger(GlobalException.class);

    //无权限异常
    @ExceptionHandler(UnauthorizedException.class)
    public Object defaultException(Exception e,HttpServletRequest request) {
    	logger.info("ContentType=="+request.getContentType());
    	if(StringUtils.isBlank(request.getContentType())) {
    		return new ModelAndView("unAuthorized");
    	}
        return CodeResult.fail(StatusCode.PERMISSION_FAIL);
    }
    
    @ExceptionHandler(Exception.class)
    public CodeResult customException(Exception e ) {
    	logger.error(e.getMessage(),e);
    	return CodeResult.fail(StatusCode.FAIL);
    }
    
    @ExceptionHandler(UnauthenticatedException.class)
    public CodeResult authorizationException(Exception e ) {
    	logger.error(e.getMessage(),e);
    	return CodeResult.fail(StatusCode.PERMISSION_FAIL);
    }
    @ExceptionHandler(RedisConnectionFailureException.class)
    public void redisConnectionFailure(Exception e) {
    	logger.error("redis连接失败，功能暂不能使用",e);
    }
    
}
